﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SharpSoft.Lexing
{
    /// <summary>
    /// 文本源
    /// </summary>
    public class TextSource : ITextSource
    {
        public TextSource(string content)
        {
            _Content = content ?? string.Empty;
        }
        private string _Content;
        public virtual string Content
        {
            get { return _Content; }
        }

        private int _Position;
        /// <summary>
        /// 获取或设置当前位置
        /// </summary>
        public int Position
        {
            get { return _Position; }
            set { _Position = value; }
        }

        public int Length
        {
            get { return Content.Length; }
        }

        /// <summary>
        /// 获取当前的字符
        /// </summary>
        public char Current
        {
            get
            {
                if (EOS())
                    return '\0';
                return this.Get(this.Position);
            }
        }

        uint ITextSource.Length
        {
            get
            {
                throw new NotImplementedException();
            }
        }

        /// <summary>
        /// 测试是否已到文件末尾
        /// </summary>
        /// <returns></returns>
        public virtual bool EOS()
        {
            if (Content==null)
            {
                return true;
            }
            return this.Position >= this.Content.Length;
        }
        /// <summary>
        /// 返回相对与当前位置指定偏移处的字符,并将指针移到该位置
        /// </summary>
        /// <param name="offset"></param>
        /// <returns></returns>
        public virtual char Next(int offset = 1)
        {
            this._Position += offset;
            return this.Current;
        }
        /// <summary>
        /// 查看相对于当前位置指定偏移处的字符
        /// </summary>
        /// <param name="offset"></param>
        /// <returns></returns>
        public virtual char Peek(int offset = 1)
        {
            return Get(this.Position + offset);
        }
        /// <summary>
        /// 获取当前源中指定位置的字符，若指定的位置超出了范围则返回'\0'
        /// </summary>
        /// <param name="index"></param>
        /// <returns></returns>
        public char Get(int index)
        {
            if (index >= this.Content.Length || index < 0)
                return '\0';
            return this.Content[index];
        }
        /// <summary>
        /// 设置游标位置
        /// </summary>
        /// <param name="index"></param>
        public void Set(int index)
        {
            _Position = index;
        }
        /// <summary>
        /// 重置游标到文本源的开始位置
        /// </summary>
        public void ResetCursor()
        {
            _Position = 0;
        }
        /// <summary>
        /// 将游标置于当前位置的指定偏移处
        /// </summary>
        /// <param name="offset"></param>
        public void MoveCursor(int offset)
        {
            _Position += offset; 
        }
    }
}
